import { useEffect, useState, useCallback, FC, useRef } from "react";
import Taro from "@tarojs/taro";
import { View } from '@tarojs/components';
import { isBleCanUse, IBleCanUseProps } from '@/utils/configDevice';
import BottomBlePopup from './BottomBlePopup';
import AlertTitleItem from './AlertTitleItem';
import sdk from "@/utils/SDK";


let haveShowBleTip = false;

interface IProps {
  onChangeBleEnable?: (info: IBleCanUseProps) => void;
}

const BleCheckTip: FC<IProps> = ({ children, onChangeBleEnable }) => {

  const [isPopupShow, setIsPopupShow] = useState<boolean>(false);
  const [isAlertShow, setIsAlertShow] = useState<boolean>(false);
  const [errorType, setErrorType] = useState<string>('BLE');
  const [errorList, setErrorList] = useState<string[]>([]);
  const isAvailableRef = useRef<boolean | undefined>()


  const showBleTip = useCallback(() => {
    if (!haveShowBleTip) {
      haveShowBleTip = true;
      setIsPopupShow(true);
    }
  }, [])

  const queryBleCanUse = useCallback(() => {
    isBleCanUse().then(({ enabled, bleEnabled, locationEnabled, errorInfo }) => {
      console.log('isBleCanUse', enabled, errorInfo);
      if (!enabled) {
        // 蓝牙初始状态为关闭
        showBleTip()
        const errorList: any = [];
        if (bleEnabled == false) {
          errorList.push('BLE');
        }
        if (locationEnabled == false) {
          errorList.push('LOCATION');
        }
        setErrorList(errorList);
        setIsAlertShow(true);
      } else {
        if (!sdk.isInit) {
          sdk.sdk?.initBle().then((res) => {
            if (res.success) {
              sdk?.startAutoScanService();
            }
          });
        }
        setIsAlertShow(false);
      }
      if (onChangeBleEnable) {
        onChangeBleEnable && onChangeBleEnable({ enabled, errorInfo });
      }
    });
  }, [showBleTip, onChangeBleEnable]);

  useEffect(() => {
    // 修改小程序权限的回来的时候，会触发这个方法，可以在这里更新一次
    Taro.onAppShow(() => {
      console.log('onAppShow');
      setTimeout(() => {
        queryBleCanUse();
      }, 1000)
    })
  }, [queryBleCanUse])

  useEffect(() => {
    queryBleCanUse();
    Taro.onBluetoothAdapterStateChange(({ available }) => {
      // 安卓实测queryBleCanUse里面如果触发了调用startBluetoothDevicesDiscovery，会触发onBluetoothAdapterStateChange回调，造成死循环，这里需要加变量判断下，变化的时候才去查询
      if (isAvailableRef.current !== available) {
        isAvailableRef.current = available;
        console.log('onBluetoothAdapterStateChange')
        queryBleCanUse();
      }

    });
  }, [queryBleCanUse]);

  const closePopup = useCallback(() => {
    setIsPopupShow(false);
  }, []);

  return (
    <>
      {isAlertShow ? (
        <View style={{ width: '100%' }}>
          {
            errorList.map(item => {
              return <AlertTitleItem errorType={item} />
            })
          }
        </View>
      ) : children}
      <BottomBlePopup errorList={errorList} isOpen={isPopupShow} closePopup={closePopup} />
    </>
  );
};

export default BleCheckTip
